package nio;

import java.nio.Buffer;
import java.nio.IntBuffer;
import java.util.logging.Logger;
import java.util.stream.IntStream;

/**
 * niobuffer 演示
 *
 * @Author winston
 * @DateTime 2022/3/31
 * @date 2022/03/31
 */
public class BufferDemo {
    static Logger logger = Logger.getLogger("");
    public static void main(String[] args) {
        var buffer = createIntBuffer(20);
        logger.info("==================================");
        writeBuffer(buffer);
        logger.info("==================================");
        flipBuffer(buffer);
        logger.info("==================================");
//        readBuffer(buffer);
        markResetBuffer(buffer);
        logger.info("==================================");
        rewindBuffer(buffer);
        logger.info("==================================");
        clearBuffer(buffer);
    }

    /**
     * 创建intbuffer
     *
     * @param capacity 能力
     * @return {@link IntBuffer}
     */
    public static IntBuffer createIntBuffer(int capacity) {
        var intBuffer = IntBuffer.allocate(capacity);
        printBufferInfo(intBuffer);
        return intBuffer;
    }

    public static void writeBuffer(IntBuffer buffer) {
        IntStream.rangeClosed(1, 10).forEach(buffer::put);
        printBufferInfo(buffer);
    }

    private static void printBufferInfo(Buffer buffer) {
        logger.info("position: " + buffer.position());
        logger.info("capacity: " + buffer.capacity());
        logger.info("limit: " + buffer.limit());
    }

    private static void flipBuffer(Buffer buffer) {
        buffer.mark();
        var flip = buffer.flip();
        printBufferInfo(buffer);
    }

    private static void clearBuffer(Buffer buffer) {
        buffer.clear();
        printBufferInfo(buffer);
    }

    private static void readBuffer(IntBuffer buffer) {
        IntStream.rangeClosed(1, buffer.limit()).forEach(i -> logger.info("Read Value: "+ buffer.get()));
        printBufferInfo(buffer);
    }

    private static void rewindBuffer(IntBuffer buffer) {
        buffer.rewind();
        printBufferInfo(buffer);
    }

    private static void markResetBuffer(IntBuffer buffer) {

        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        buffer.mark();
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        buffer.reset();
        System.out.println(buffer.get());
        System.out.println(buffer.get());
        System.out.println(buffer.get());
    }
}
